const CryptoJS = require('crypto-js');
module.exports = Behavior({
  methods: {
    post: function (url, data) {
        data["reason"] && (data["reason"] += "-移动端审核");
        const key_url = ['pfep2_api', 'gm_user', 'container_manage_api', 'package_integrated_api', 'vehicle_reservation_api']
        const flag = this.containsAnyRegex(url, key_url)
        if (flag) {

            data = {
                "hard_to_guess": this.aesEncrypt(JSON.stringify(data))
            }
        }
      let token = "";
      try {
        var value = wx.getStorageSync('token')
        if (value) {
          token = value;
        }
      } catch (e) {
        // Do something when catch error
        console.log(e)
      }
      return new Promise((resolve, reject) => {
        wx.request({
          url,
          data,
          header: {
            "Authorization": token
          },
          dataType: "json",
          method: "POST",
          success(res) {
            const result = res.data;
            const code = result.code;
            if (code == 20000) {
              resolve(result);
            } else {
              // 50006删除不跳转登录页
              // 50001删除 - 兼顾游客身份
              if ([50001,50002, 50003, 50004].includes(code)) {
                wx.clearStorage()
                wx.reLaunch({
                  url: '/pages/login1/login',
                });
                wx.showToast({
                  title: '请重新登录！',
                  icon: "error"
                });
              }
              if (code === 50006 && result.msg !== "未注册") {
                wx.clearStorage()
                wx.reLaunch({
                  url: '/pages/login1/login',
                });
                wx.showToast({
                  title: '请重新登录！',
                  icon: "error"
                });
              }
              // console.log("result",result);                
              reject(result);
            }
          },
          fail(res) {
            console.log(res);

            const result = {
              code: "50010",
              msg: "网络出现异常",
              data: {}
            }
            reject(result);
          }
        });
      })
    },
    get: function (url, data) {
        data["reason"] && (data["reason"] += "-移动端审核");
            const key_url = ['pfep2_api', 'gm_user', 'container_manage_api', 'package_integrated_api', 'vehicle_reservation_api']
            const flag = this.containsAnyRegex(url, key_url)
            if (flag) {

                data = {
                    "hard_to_guess": this.aesEncrypt(JSON.stringify(data))
                }
            }
      let token = "";
      try {
        var value = wx.getStorageSync('token')
        if (value) {
          token = value;
        }
      } catch (e) {
        // Do something when catch error
        console.log(e)
      }
      return new Promise((resolve, reject) => {
        wx.request({
          url,
          data,
          header: {
            "Authorization": token
          },
          dataType: "json",
          method: "get",
          success(res) {
            const result = res.data;
            const code = result.code;
            if (code == 20000) {
              resolve(result);
            } else {
              if ([50001, 50002, 50003, 50004].includes(code)) {
                wx.clearStorage()
                wx.reLaunch({
                  url: '/pages/login1/login',
                });
                wx.showToast({
                  title: '请重新登录！',
                  icon: "error"
                });
              }
              if (code === 50006 && result.msg !== "未注册"||code === 50006 && result.msg !== "系统未注册该用户") {
                wx.clearStorage()
                wx.reLaunch({
                  url: '/pages/login1/login',
                });
                wx.showToast({
                  title: '请重新登录！',
                  icon: "error"
                });
              }
              // console.log("result",result);                
              reject(result);
            }
          },
          fail(res) {
            console.log(res);
            const result = {
              code: "50010",
              msg: "服务器出现错误！",
              data: {}
            }
            reject(result);
          }
        });
      })
    },
    containsAnyRegex(str, substrings) {
        const pattern = substrings.join('|'); // 拼成 '微信|支付宝|百度'
        return new RegExp(pattern).test(str);
    },
    aesEncrypt(data) {
        const KEY = 'vE6rY8VG6ZE8gnn6'; // 16 字节密钥（AES-128）
        const IV = 'TXxGgsYg4VITzzEe';  // 16 字节偏移量
        const key = CryptoJS.enc.Utf8.parse(KEY);
        const iv = CryptoJS.enc.Utf8.parse(IV);

        const encrypted = CryptoJS.AES.encrypt(data, key, {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.ZeroPadding
        });

        return encrypted.ciphertext.toString(CryptoJS.enc.Base64)

    },
      // 时间处理函数 (不要时分)
      GMTToStr1(time) {
        const date = new Date(time) - 60000 * 60 * 8;
        const result = new Date(date);
        let hour = result.getHours();
        if (hour < 10) {
            hour = "0" + hour;
        }
        let minute = result.getMinutes();
        if (minute < 10) {
            minute = "0" + minute;
        }
        let month = result.getMonth() + 1;
        if (month < 10) {
            month = "0" + month;
        }
        let d = result.getDate();
        if (d < 10) {
            d = "0" + d;
        }
        let Str = result.getFullYear() + '-' + month + '-' + d;
        return Str
    },
    getTmplIds() {
        let tmplIds = ['Qq4EMCt24ZVzeR74sHCcdCgZyo7pus8Bf9knNoUHPpM']
        return tmplIds
    },
    // 控制页面权限
    checkAuth(e) {
      // console.log(e);
      let key = e.currentTarget.dataset.row_data
      let url = e.currentTarget.dataset.baseurl
      let auth_url = e.currentTarget.dataset.get_auth
      this.post(url, {}).then(res => {
        wx.navigateTo({
          url: key,
        })
      }).catch(err => {
        if (err.code === 50005 || err.code === 50006) {
          if (auth_url !== "0") {
            wx.showModal({
              title: err.msg,
              content: '',
              confirmText: '去申请',
              success(res) {
                if (res.confirm) {
                  // console.log(auth_url);
                  wx.navigateTo({
                    url: auth_url,
                  })
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          } else {
            wx.showToast({
              title: err.msg,
              icon: 'error'
            })
          }


        } else {
          wx.requestSubscribeMessage({
            tmplIds: ['Qq4EMCt24ZVzeR74sHCcdCgZyo7pus8Bf9knNoUHPpM'],
          })
          wx.navigateTo({
            url: key,
          })
        }

      })

    },
    getDaysBetweenDates(date1, date2) {
      // 将日期字符串转换为时间戳
      var t1 = new Date(date1).getTime();
      var t2 = new Date(date2).getTime();
      let differenceInMillis = t2 - t1;
      // 毫秒差值
      // 秒差值
      let differenceInSeconds = Math.floor(differenceInMillis / 1000);
      // 分钟差值
      let differenceInMinutes = Math.floor(differenceInSeconds / 60);
      // 小时差值
      let differenceInHours = Math.floor(differenceInMinutes / 60);
      // console.log(differenceInHours);
      // 天差值
      let differenceInDays = Math.floor(differenceInHours / 24);
      return (differenceInHours / 24).toFixed(1)
      // 计算两个时间戳之间的天数

    },

    // 获取当前年月日
    gainDate() {
      let date = new Date(new Date().getTime());
      let year = date.getFullYear();
      let month = (date.getMonth() + 1).toString().padStart(2, '0')
      let day = date.getDate();
      if(day < 10){
        day =  "0" + day
      }
      const today = year + '-' + month + '-' + day
      return today
    },
    
    // 获取上个月当前年月日
    gainBeforeDate() {
      let date = new Date(new Date().getTime());
      let year = date.getFullYear();
      let month = (date.getMonth() ).toString().padStart(2, '0')
      let day = date.getDate();
      if(day < 10){
        day =  "0" + day
      }
      const today = year + '-' + month + '-' + day
      return today
    },
    // 时间处理函数
    GMTToStr(time) {
      const date = new Date(time) - 60000 * 60 * 8;
      const result = new Date(date);
      let hour = result.getHours();
      if (hour < 10) {
        hour = "0" + hour;
      }
      let minute = result.getMinutes();
      if (minute < 10) {
        minute = "0" + minute;
      }
      let month = result.getMonth() + 1;
      if (month < 10) {
        month = "0" + month;
      }
      let d = result.getDate();
      if (d < 10) {
        d = "0" + d;
      }
      let Str = result.getFullYear() + '-' + month + '-' + d + ' ' + hour + ":" + minute;
      return Str
    },
    // 日期处理函数
    formatDate(date) {
      let taskStartTime
      if (date.getMonth() < 9) {
        taskStartTime = date.getFullYear() + "-0" + (date.getMonth() + 1) + "-"
      } else {
        taskStartTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-"
      }
      if (date.getDate() < 10) {
        taskStartTime += "0" + date.getDate()
      } else {
        taskStartTime += date.getDate()
      }
      taskStartTime += " " + date.getHours() + ":" + date.getMinutes()
      // console.log(taskStartTime);
      // console.log(a.substr(-1));
      return taskStartTime;
    },
      // 跳转企业版小程序
      toPersonalApp() {
        wx.navigateToMiniProgram({
            appId: 'wxf1c5e32583aff4f4',
            path: 'packageB/pages/package/task_manager/task_manager', // 目标页面路径
            envVersion: 'release', // 目标小程序版本（develop/test/release）
            success(res) { /* 成功回调 */ },
            fail(err) { /* 失败回调 */ }
        });
    },
    // 日期处理函数不要时分
    formatDate1(date) {
      let taskStartTime
      if (date.getMonth() < 9) {
        taskStartTime = date.getFullYear() + "-0" + (date.getMonth() + 1) + "-"
      } else {
        taskStartTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-"
      }
      if (date.getDate() < 10) {
        taskStartTime += "0" + date.getDate()
      } else {
        taskStartTime += date.getDate()
      }
      // taskStartTime += " " + date.getHours() + ":" + date.getMinutes()
      return taskStartTime;
    },
    // 日期补零函数
    formatNowTime() {
      let date = new Date(new Date().getTime());
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      let hour = date.getHours();
      let minute = date.getMinutes();
      let second = date.getSeconds();
      month = month > 9 ? month : "0" + month;
      day = day > 9 ? day : "0" + day;
      hour = hour > 9 ? hour : "0" + hour;
      minute = minute > 9 ? minute : "0" + minute;
      second = second > 9 ? second : "0" + second;
      return `${year}-${month}-${day} ${hour}:${minute}`;
    },

     formatDateTimeSe(gmtString) {
        const date = new Date(gmtString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      
    
    },
    
    
    // 验证手机号
    checkPhone(val) {
      let phone_num = val
      // console.log(phone_num.length);
      if (phone_num.length == 11) {
        let phoneReg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
        if (!phoneReg.test(phone_num)) {
          wx.showToast({
            title: '手机格式错误',
            icon: 'error'
          })
          return false
        }
      }
      return true
    },


  }
})